﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Ict.DataAccess;
using CSF.BusinessCore.BLL;
using CSF.Security.Data;

namespace CSF.Security.BLL
{
    /// <summary>
    /// 用户角色业务类
    /// </summary>
    public class UserRoleBLL : TransactionConfigLogic<UserRole>
    {
        /// <summary>
        /// 获取指定用户角色的权限集合
        /// </summary>
        /// <param name="roleId">用户角色Id</param>
        /// <returns></returns>
        public IEnumerable<int> GetPermissions(int roleId)
        {
            RolePermissionBLL bll = new RolePermissionBLL();
            return bll.GetPermissionIdsByUser(roleId);
        }

        /// <summary>
        /// 批量设置用户角色的权限
        /// Modified By: Robin
        /// Modified Time: 2011-5-2
        /// 在插入前，将用户角色的权限先删除掉。
        /// </summary>
        /// <param name="roleId">角色id</param>
        /// <param name="permissionIds">权限集合</param>
        public void SetPermission(int roleId, IEnumerable<int> permissionIds, string createBy)
        {
            using (Executor exec = DataContext.CreateExecutor())
            {
                try
                {
                    exec.BeginTransaction();

                    RolePermissionBLL bll = new RolePermissionBLL();

                    // andy-peng add code 2011-09-02  在插入前，将用户角色的权限先删除掉
                    bll.Delete(p => p.RoleId == roleId, exec);

                    foreach (var id in permissionIds)
                    {
                        RolePermission rolePermisstion = new RolePermission()
                        {
                            RoleId = roleId,
                            PermissionId = id,
                            CreateBy = createBy
                        };
                        try
                        {
                            bll.Insert<RolePermission>(rolePermisstion, null, exec);
                        }
                        catch (PrimaryKeyException)
                        {
                            // 如果出现主键重复，表明关联已存在，故不必理会
                        }
                    }
                    exec.CommitTransaction();
                }
                catch
                {
                    exec.RollbackTransaction();
                }
            }
        }
    }
}
